package com.joker.order.consumer;

import com.alibaba.fastjson.JSONObject;
import com.joker.common.redis.service.RedisService;
import com.joker.common.security.utils.SecurityUtils;
import com.joker.order.config.RabbitMQConfig;
import com.joker.order.constant.OrderConstant;
import com.joker.order.domain.dto.OrderDTO;
import com.joker.order.service.OrderService;
import com.joker.system.common.model.LoginUser;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


@Component
public class OrderConsumer {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisService redisService;

    @RabbitListener(queues = {RabbitMQConfig.ORDER_QUEUE})
    public void consume(String order) {

        OrderDTO orderDTO = JSONObject.parseObject(order, OrderDTO.class);

        if (orderService.skuInventory(orderDTO) == 0){

            redisService.setCacheObject(OrderConstant.ORDER+orderDTO.getOrderNo(), OrderConstant.ORDER_STATUS_FAIL);

        }else {

//            LoginUser loginUser = SecurityUtils.getLoginUser();
//            Long userid = loginUser.getUserid();

            orderService.createOrder(orderDTO);

            redisService.setCacheObject(OrderConstant.ORDER+orderDTO.getOrderNo(), OrderConstant.ORDER_STATUS_FINISH);
            List<Long> skuIds = Arrays.stream(orderDTO.getSkuIds())
                    .collect(Collectors.toList());

            for (Long skuId : skuIds) {
                String userCart = "cart:" + 1;
                redisService.deleteCacheMapValue(userCart, skuId.toString());
            }

        }
    }


}
